package com.easyskool.composer;

import java.io.IOException;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.codehaus.jackson.JsonParseException;
import org.codehaus.jackson.map.JsonMappingException;
import org.codehaus.jackson.map.ObjectMapper;
import org.json.JSONException;
import org.json.JSONObject;

import com.easyskool.constants.CommonConstants;
import com.easyskool.constants.DataBaseConstants;
import com.easyskool.constants.EmailLinkConstants;
import com.easyskool.constants.MessageConstants;
import com.easyskool.constants.TableNames;
import com.easyskool.dao.BaseDao;
import com.easyskool.exception.DaoException;
import com.easyskool.hibernate.model.ContactForms;
import com.easyskool.hibernate.model.UserAuthorization;
//import com.easyskool.hibernate.model.AccessAuthorization;
//import com.easyskool.hibernate.model.AdminDetails;
//import com.easyskool.hibernate.model.SchoolRequest;
import com.easyskool.util.mailUtil;
import com.easyskool.utilfunction.NullObjects;
import com.easyskool.utilfunction.UtilFunctions;
import com.google.gson.JsonObject;
import com.ivp.cloud.stratus.logger.LoggingUtil;

@SuppressWarnings({ "unchecked", "serial" })
public class UserServiceComposer implements Serializable {

	BaseDao baseDao;
	private static LoggingUtil logger = (LoggingUtil) LoggingUtil
			.getLogger(UserServiceComposer.class.getName());

	public BaseDao getBaseDao() {
		if (NullObjects.isNull(baseDao)) {
			baseDao = new BaseDao();
		}
		return baseDao;
	}
//
	public UserAuthorization validateCredentials(String code, String password) throws Exception {
		List<UserAuthorization> users= new ArrayList<UserAuthorization>();
		HashMap<String,Object> params =new HashMap<String,Object> ();
		params.put("uaCode", code);
		params.put("uaEmail", code);
		params.put("uaPassword", password);
			users=getBaseDao().customQuery("from UserAuthorization where ( uaCode=:uaCode OR uaEmail=:uaEmail) AND uaPassword=:uaPassword" , params);
		logger.info("Number of users found: "+users.size());
		if(users==null|| users.size()==0)
		return null;
		else
		return users.get(0);
	}
	
	public List<ContactForms> getUncontacted() throws Exception {
		List<UserAuthorization> users= new ArrayList<UserAuthorization>();
		Map<String, Object> whereMap=new HashMap<String, Object> ();
		whereMap.put("status", 0);
	return	getBaseDao().find(ContactForms.class, whereMap);
	}
//
//	public String insertUser(String user, String insertValues)
//			throws JsonParseException, JsonMappingException, IOException,
//			InstantiationException, IllegalAccessException, DaoException {
//
//		ObjectMapper mapper = new ObjectMapper();
//		AccessAuthorization userToInsert = new AccessAuthorization();
//		userToInsert = mapper
//				.readValue(insertValues, AccessAuthorization.class);
//		System.out.println("map : " + userToInsert);
//		System.out.println(" map : " + userToInsert.getAaCode());
//		getBaseDao().insert(TableNames.accessAuthorization, insertValues);
//
//		return "saved";
//	}
//
	/**
	 * Inserts the school request in the database
	 * 
	 * @param user
	 * @param insertValues
	 * @return success or fail
	 */
	public boolean insertRequest(String formData) {
		logger.info("Entering insertSchoolRequest ");
		JsonObject json = new JsonObject();
		try {
			ObjectMapper mapper = new ObjectMapper();
			ContactForms contactForm = new ContactForms();
			contactForm = mapper.readValue(formData, ContactForms.class);
			Date d = new Date();
			contactForm.setCreatedDate(d);
			contactForm.setModifiedDate(d);
			contactForm.setModifiedBy(CommonConstants.WEBSITE);
			d.setDate(d.getDate()+1);
			contactForm.setCfFollowupDate(d.toString());
			contactForm.setCreatedBy(CommonConstants.WEBSITE);
			contactForm.setUaCode(UtilFunctions.generateString(10));
			
			ContactForms result=getBaseDao().insertWithObject(ContactForms.class, contactForm);
			if(result!=null)
			{
				new mailUtil(contactForm.getCfEmail(), "Request has been registered", "Your request with request id "+result.getRowId()+" has been registered");
				return true;
			}
			else
				return false;
		} catch (Exception e) {
			logger.error(e);
			System.out.println(e);
			return false;
		}
	}
//
//	public String setDetails(String user, String whereClause,
//			String updateClause) {
//
//		int result = 0;
//		try { // {"id":"21","admAddress":"","admCity":"","admState":"","admCountry":"","admPin":"","aaSecurityQ1":"","aaSecurityA1":"","aaSecurityQ2":"","aaSecurityA2":""}
//				// :whereClause
//			// {"code":"21"} :updateClause
//			// Map<String, Object> whereClause, Map<String, Object> updateClause
//			System.out.println("Data Coming in setdetails Composer" + user
//					+ " :USER " + whereClause + " :whereClause " + updateClause
//					+ " :updateClause");
//			JSONObject jsonObj1 = new JSONObject(whereClause);
//			Map<String, Object> whereMap = new HashMap<String, Object>();
//			whereMap.put("aaCode", jsonObj1.getInt("code"));
//			String type = jsonObj1.getString("type");
//			JSONObject jsonObj = new JSONObject(updateClause);
//			Map<String, Object> updateMap = new HashMap<String, Object>();
//			if (DataBaseConstants.SHIRO_ROLE_ADMIN.equals(type)) {
//				updateMap.put("admCountry", jsonObj.getString("admCountry"));
//				updateMap.put("admAddress", jsonObj.getString("admAddress"));
//				updateMap.put("admCity", jsonObj.getString("admCity"));
//				updateMap.put("admState", jsonObj.getString("admState"));
//				updateMap.put("admPin", jsonObj.getString("admPin"));
//				result = getBaseDao().updateWithoutFullobject(
//						AdminDetails.class, whereMap, updateMap);
//			} else if (DataBaseConstants.SHIRO_ROLE_MODERATOR.equals(type)) {
//				updateMap.put("mdrCountry", jsonObj.getString("mdrCountry"));
//				updateMap.put("mdrAddress", jsonObj.getString("mdrAddress"));
//				updateMap.put("mdrCity", jsonObj.getString("mdrCity"));
//				updateMap.put("mdrState", jsonObj.getString("mdrState"));
//				updateMap.put("mdrPin", jsonObj.getString("mdrPin"));
//				result = getBaseDao().updateWithoutFullobject(
//						AdminDetails.class, whereMap, updateMap);
//			} else if (DataBaseConstants.SHIRO_ROLE_TEACHER.equals(type)) {
//				updateMap.put("tchCountry", jsonObj.getString("tchCountry"));
//				updateMap.put("tchAddress", jsonObj.getString("tchAddress"));
//				updateMap.put("tchCity", jsonObj.getString("tchCity"));
//				updateMap.put("tchState", jsonObj.getString("tchState"));
//				updateMap.put("tchPin", jsonObj.getString("tchPin"));
//				result = getBaseDao().updateWithoutFullobject(
//						AdminDetails.class, whereMap, updateMap);
//			} else if (DataBaseConstants.SHIRO_ROLE_PARENT.equals(type)) {
//				updateMap.put("prtCountry", jsonObj.getString("prtCountry"));
//				updateMap.put("prtAddress", jsonObj.getString("prtAddress"));
//				updateMap.put("prtCity", jsonObj.getString("prtCity"));
//				updateMap.put("prtState", jsonObj.getString("prtState"));
//				updateMap.put("prtPin", jsonObj.getString("prtPin"));
//				result = getBaseDao().updateWithoutFullobject(
//						AdminDetails.class, whereMap, updateMap);
//			} else if (DataBaseConstants.SHIRO_ROLE_STUDENT.equals(type)) {
//				updateMap.put("stCountry", jsonObj.getString("stCountry"));
//				updateMap.put("stAddress", jsonObj.getString("stAddress"));
//				updateMap.put("stCity", jsonObj.getString("stCity"));
//				updateMap.put("stState", jsonObj.getString("stState"));
//				updateMap.put("stPin", jsonObj.getString("stPin"));
//				result = getBaseDao().updateWithoutFullobject(
//						AdminDetails.class, whereMap, updateMap);
//			}
//
//			if (result == 1) {
//				result = 0;
//				updateMap.clear();
//				updateMap
//						.put("aaSecurityQ1", jsonObj.getString("aaSecurityQ1"));
//				updateMap
//						.put("aaSecurityA1", jsonObj.getString("aaSecurityA1"));
//				updateMap
//						.put("aaSecurityQ2", jsonObj.getString("aaSecurityQ2"));
//				updateMap.put("aaPassword", jsonObj.getString("aaPassword"));
//				updateMap
//						.put("aaSecurityA2", jsonObj.getString("aaSecurityA2"));
//				updateMap.put("aaIsBlocked", 0);
//				result = getBaseDao().updateWithoutFullobject(
//						AccessAuthorization.class, whereMap, updateMap);
//			}
//			if (result == 1) {
//
//				System.out.println("REturning in setDetails Service " + result);
//				return CommonConstants.SUCCESS;
//			}
//
//		} catch (DaoException e) {
//			e.printStackTrace();
//			System.out.println("REturning in setDetails Service " + result);
//			return CommonConstants.FAIL;
//		} catch (JSONException e) {
//			e.printStackTrace();
//			System.out.println("REturning in setDetails Service " + result);
//			return CommonConstants.FAIL;
//		} catch (Exception e) {
//			e.printStackTrace();
//			System.out.println("REturning in setDetails Service " + result);
//			return CommonConstants.FAIL;
//		}
//
//		System.out.println("REturning in setDetails Service " + result);
//		return CommonConstants.FAIL;
//	}
//
//	public int sendPassword(String user, String whereClause)
//			throws JSONException, DaoException {
//
//		System.out.println("Data coming in sendPassord Composer: " + user
//				+ " :user " + whereClause + " :whereClause");
//		JSONObject jsonObj = new JSONObject(whereClause);
//		Map<String, Object> whereMap = new HashMap<String, Object>();
//		whereMap.put("aaSecurityQ1", jsonObj.getString("aaSecurityQ1"));
//		whereMap.put("aaSecurityA1", jsonObj.getString("aaSecurityA1"));
//		whereMap.put("aaSecurityQ2", jsonObj.getString("aaSecurityQ2"));
//		whereMap.put("aaEmail", jsonObj.getString("email"));
//		whereMap.put("aaSecurityA2", jsonObj.getString("aaSecurityA2"));
//		List<AccessAuthorization> users = getBaseDao().find(
//				AccessAuthorization.class, whereMap);
//		System.out.println("Data coming out of composer : " + users.size());
//		if (users.size() == 1) {
//			System.out.println("Sending mail to: " + users.get(0).getAaEmail());
//			try {
//				new mailUtil(users.get(0).getAaEmail(),
//						"For Password @ easyskool.com", "Your Password is "
//								+ users.get(0).getAaPassword());
//			} catch (Exception e) {
//				return -1;
//			}
//			return users.size();
//		} else if (users.size() != 1)
//			return 0;
//		else
//			return -1;
//
//	}
//
//	public int changePasswordDetails(String user, String whereClause)
//			throws JSONException, DaoException {
//		System.out.println("Data coming in changePasswordDetails Composer: "
//				+ user + " :user " + whereClause + " :whereClause");
//		JSONObject jsonObj = new JSONObject(whereClause);
//		Map<String, Object> whereMap = new HashMap<String, Object>();
//		whereMap.put("aaEmail", jsonObj.getString("email"));
//		whereMap.put("aaPassword", jsonObj.getString("aaLastPassword"));
//		List<AccessAuthorization> returnData = getBaseDao().find(
//				TableNames.accessAuthorization, whereMap);
//		System.out.println("Number of users returned: " + returnData.size()
//				+ " ID: " + returnData.get(0).getAaCode());
//		if (returnData.size() == 1) {
//			String oldPwd = returnData.get(0).getAaPassword();
//			whereMap.clear();
//			whereMap.put("aaCode", returnData.get(0).getAaCode());
//			Map<String, Object> updateMap = new HashMap<String, Object>();
//			updateMap.put("aaPassword", jsonObj.getString("aaPassword"));
//			updateMap.put("aaLastPassword", oldPwd);
//			int rowsAffected = getBaseDao().updateWithoutFullobject(
//					TableNames.accessAuthorization, whereMap, updateMap);
//			System.out
//					.println("RowsAffected in changePasswordDetails composer: "
//							+ rowsAffected);
//			if (rowsAffected == 1) {
//				try {
//					new mailUtil(returnData.get(0).getAaEmail(),
//							"For Password @ easyskool.com",
//							"Your Password has been changed");
//				} catch (Exception e) {
//					e.printStackTrace();
//					return -1;
//				}
//				System.out
//						.println("Return in changePasswordDetails composer: 1");
//				return 1;
//
//			} else
//				System.out
//						.println("Return in changePasswordDetails composer: -1");
//			return -1;
//		}
//		System.out.println("Return in changePasswordDetails composer: -1");
//		return -1;
//	}
//
}
